import React,{useEffect,useState} from "react";
import {
  Text,
  View,
  StyleSheet,
  TouchableHighlight,
  TouchableOpacity,
  Linking,
  ScrollView,
  Alert,
  TextInput,
  Platform,
  Image,
  NativeModules, NativeEventEmitter
} from "react-native";
import * as S from "../Home/styles";
import { Avatar, HStack, Center, NativeBaseProvider ,ChevronRightIcon,useToast,ArrowBackIcon} from "native-base";
import {launchImageLibrary,launchCamera} from 'react-native-image-picker';
import { /*RFValue*/ } from "react-native-responsive-fontsize";
import Icon from 'react-native-vector-icons/Ionicons';
import { useGlobal } from '../../utils/GlobalContext';
import { getUeser,phoneLogin } from "../../services/user";
import { showToast } from "../../utils/toast";

// import NetInfo from '@react-native-community/netinfo';

// import * as WeChat from 'react-native-wechat-lib';
// import { getApiVersion, registerApp, openWXApp,isWXAppSupportApi, sendAuthRequest, shareText } from 'react-native-wechat-lib';

import Spinner from 'react-native-loading-spinner-overlay';


const Loading = ({ loading, text }) => {
  // if (!loading) {
  //   return null;
  // }

  return (<Spinner
    visible={loading}
    textContent={text}
    cancelable={true}
    // customIndicator={ <Spinner2 size="lg" /> }
    // indicatorStyle={{margin:0,marginBottom:0}}
    overlayColor={'rgba(0, 0, 0, 0.5)'}
    textStyle={{ color: '#FFF',fontSize:16,fontFamily:'HarmonyOS Sans SC',fontWeight:'700' }}
    animation="fade"
  />
  );
};


// WeChat.registerApp('appid', 'wxc5675acb82e069f5');
// WeChat.registerApp('wxc5675acb82e069f5');
const { WechatUtils } = NativeModules;
const wechatEmitter = new NativeEventEmitter(WechatUtils);


const Title = ({navigation}:any)=>{
  return(
    <View style={styles.titleBox}>
      <TouchableOpacity
        style={styles.backBtn}
        onPress={() => {
          navigation.goBack()
        }}
      >
        <ArrowBackIcon size="5" />
      </TouchableOpacity>
    </View>
  )
}

const LoginBox = ({route,navigation,setLoading}:any)=>{

  // React.useEffect(() => {
  //   registerApp('wxf2ca8bb0bd6ee8f0', '').then((res) => {
  //     // Alert.alert("registerApp: " + res)
  //   });

  // }, []);
  // React.useEffect(() => {

  //   if (Platform.OS === 'ios') {
  //     WechatUtils.registerApp('wxf2ca8bb0bd6ee8f0');
  //   } else {
  //     registerApp('wxf2ca8bb0bd6ee8f0', 'universalLink').then((res) => {
  //       console.log("registerApp: " + res)
  //       getApiVersion().then((num) => {
  //         console.log("test: " + num)
  //         // setVersionNumber(num)
  //         // openWXApp().then()
  //       })
  //     });
  //   }
  // }, []);

  const { state, dispatch } = useGlobal();
  const toast = useToast();

  const [phone,setPhone] = useState('')
  const [password,setPassword] = useState('')
  const [agreementStatus,setAgreementStatus] = useState(false)





  const onChange = (text:any,type:number)=>{
    if(type == 1){
      setPhone(text)
    }else{
      setPassword(text)
    }
  }


  const getUserInfo = ()=>{
    getUeser().then((res:any)=>{
      dispatch({ type:'SET_USER' , payload:res.data })
    })
  }



  const phoneLoginBtn = ()=>{
    let obj = {
      username:phone,
      password,
    }
    if(!phone){
      // toast.show({
      //   description: "请输入手机号",
      //   placement: "bottom"
      // })
      showToast("", "", "请输入手机号");
      return
    }

    if(!password){
      // toast.show({
      //   description: "请输入密码",
      //   placement: "bottom"
      // })
      showToast("", "", "请输入密码");
      return
    }

    if(!agreementStatus){
      // toast.show({
      //   description: "请同意《用户协议》《隐私协议》",
      //   placement: "bottom"
      // })
      showToast("", "", "请同意《用户协议》《隐私协议》");
      return
    }

    // console.log(obj)
    setLoading(true)
  
    phoneLogin(obj).then(res=>{
      // console.log(res)
      setLoading(false)
      console.log(1231231)
      console.log(res.token)
      console.log(1231231)
      dispatch({ type:'SET_TOKEN' , payload:res.token })
      dispatch({ type:'SET_USER' , payload:{} })
      getUserInfo()
      navigation.replace('Home')
    }).catch(()=>{
      setLoading(false)
    })
  }

  return(
    <View style={styles.loginBox}>
      <View style={styles.titleContent}>
        <Text style={styles.contentOne}>密码登录</Text>
        <Text style={styles.contentTwo}>未注册手机号验证后自动登录</Text>
      </View>
      <View style={styles.boxInput}>
        <View>
          <TextInput
            style={styles.input}
            placeholder='手机号或邮箱'
            placeholderTextColor='#8E8E93'
            onChangeText={text => onChange(text,1)}
            value={phone}
          />
        </View>
        <View>
          <TextInput
            textContentType="password"
            secureTextEntry={true}
            style={styles.input}
            placeholder='密码'
            placeholderTextColor='#8E8E93'
            onChangeText={text => onChange(text,2)}
            value={password}
          />
        </View>
        <View style={styles.agreementBox}>
          <TouchableOpacity onPress={() => {
            setAgreementStatus(agreementStatus ? false : true)
          }}>
            <View style={styles.agreementBoxCheck}>
              {
                !agreementStatus
                ?
                <Image style={{marginRight:8, width:18,height:18}} source={require("../../assets/images/profile/radio.png")} alt="" />
                :
                <Image style={{marginRight:8, width:18,height:18}} source={require("../../assets/images/profile/radio_active.png")} alt="" />
              }
              
              <Text style={styles.agreementBoxCheckText}>阅读并同意</Text>
            </View>
          </TouchableOpacity>
          
          
          <TouchableOpacity onPress={() => {
            navigation.navigate('WebView',{name:'隐私协议',path:'https://xiaot.club/doc/#/'})
          }}>
            <View style={styles.agreementBoxView}>
              <Text style={styles.agreementBoxViewText}> 《用户协议》《隐私协议》</Text>
            </View>
          </TouchableOpacity>
          

          
        </View>

        <View>

          <TouchableOpacity style={[styles.loginBtn,{backgroundColor:'#4371B1'}]} onPress={() => {
              phoneLoginBtn()
          }}>
            <Text style={[styles.loginBtnText,{color:'#fff'}]}>登录</Text>
          </TouchableOpacity>
          <TouchableOpacity style={[styles.loginBtn,{backgroundColor:'#F2F2F7'}]} onPress={() => {
              navigation.navigate('CodeLogin')
          }}>
            <Text style={[styles.loginBtnText,{color:'#2C2C2E'}]}>验证码登录</Text>
          </TouchableOpacity>
        
          
        </View>

        <View style={styles.btnBottom}>
          <TouchableOpacity onPress={() => {
              navigation.navigate('ResetPassword')
          }}>
            <Text style={styles.btnBottomText}>忘记密码？</Text>
          </TouchableOpacity>
          <TouchableOpacity onPress={() => {
              navigation.navigate('Sign')
          }}>
            <Text style={styles.btnBottomText}>注册账号</Text>
          </TouchableOpacity>
          
        </View>
      </View>

      


    </View>
  )
}


const Login = ({route,navigation}:any) => {

  const [ loading,setLoading ] = useState(false)
  React.useEffect(() => {
    // if(Platform.OS == 'ios'){
    //   const checkNetworkStatus = async () => {
    //     const netInfoState = await NetInfo.fetch();
    //     const isConnected = netInfoState.isConnected;
  
    //     if (isConnected) {
    //       console.log('Internet is reachable');
    //       // 执行与网络连接相关的操作
    //     } else {
    //       console.log('No Internet Connection');
    //       // 执行与无网络连接相关的操作
    //     }
    //   };
    //   checkNetworkStatus();
    // }
    

  }, []);



  



  return (
    <S.GrayContainer style={{backgroundColor:'#FFFFFF'}}>
      <NativeBaseProvider>
       <View style={styles.container}>
          {/* <Title navigation={navigation}/> */}
          <ScrollView style={{height:'65%'}} showsVerticalScrollIndicator={false}>
            <LoginBox setLoading={setLoading} route={route} navigation={navigation}/>
            
          </ScrollView>
          {/* <WXlogin/> */}
          

         
       </View>
       <Loading loading={loading} text={'登录中...'}/>
      </NativeBaseProvider>
      
      
    </S.GrayContainer>
  );
};

// const WXlogin = ({route,navigation}:any) =>{


//   useEffect(()=>{

//     const handleWechatReq = (response) => {
//       wechatReq(response);
//     };
//     const handleWechatResp = (response) => {
//       wechatResp(response);
//     };
//     const wchatRepListener = wechatEmitter.addListener(
//         'WeChat_Req',
//         handleWechatReq
//     );
//     const wchatRespListener = wechatEmitter.addListener(
//         'WeChat_Resp',
//         handleWechatResp
//     );
//     return () => {
//       wchatRepListener && wchatRepListener.remove();
//       wchatRespListener && wchatRespListener.remove();
//     };
//   },[])

//   const wechatReq = (response) => {
//     console.log('---wechatReq--response-',response)
//   };

//   const wechatResp = (response) => {
//     console.log('---wechatResp--response-',response)
//   };

//   const handleWeChatLogin = async () => {
//     // Alert.alert('123')
//     // openWXApp()
//     try {
//       // isWXAppSupportApi().then(res=>{
//       //   console.log(res)
//       // })
//       if (Platform.OS === 'ios') {
//         WechatUtils.sendAuthRequest('snsapi_userinfo','123456',(res)=>{
//           console.log('---res--',res);
//         })
//       } else {
//         console.log('--handleWeChatLogin--sendAuthRequest--')
//         sendAuthRequest('snsapi_userinfo','123456').then((response: any) => {
//           // todo 登录 response.code
//           Alert.alert('登录成功，code: ' + response.code)
//         })
//         .catch(error => {
//           Alert.alert('123')
//           console.log(error)
//           let errorCode = Number(error.code);
//           if (errorCode === -2) {
//             Alert.alert('已取消授权登录')
//           } else {
//             Alert.alert('微信授权登录失败')
//           }
//         });
//       }
//     } catch (error) {
//       // 处理登录失败
//       Alert.alert('登录失败', error.message);
//     }
//   }
//   return(
//     <View style={styles.wxLoginBox}>
//       <View style={styles.textBox}>
//         <View style={styles.boxLine}></View>
//         <Text style={styles.otherLoginText}>其他登录方式</Text>
//         <View style={styles.boxLine}></View>
//       </View>

//       <TouchableOpacity onPress={() => {
//         handleWeChatLogin()
//       }}>
//         <Image style={{width:40,height:40}} source={require("../../assets/images/profile/icon_wechat.png")} alt="" />
//       </TouchableOpacity>
      
//     </View>
//   )
// }

export default Login;
const styles = StyleSheet.create({
  container:{
    height:"100%",
    width:'100%',
    // alignItems:'center',
    paddingHorizontal:24,
    
  },
  titleBox:{
    width:'100%',
    position:'relative',
    alignItems:'center',
    height:40,
    justifyContent:"center",
    marginBottom:26,
  },
  backBtn:{
    position:'absolute',
    left:0,
    backgroundColor:'#fff',
    width:40,
    height:40,
    display:'flex',
    alignItems:'center',
    justifyContent:'center',
    borderRadius:100,
    
    shadowColor: Platform.OS === 'android' ? '' : 'rgba(0, 0, 0, 0.08)', // 阴影颜色
    shadowOffset: { width: 0, height: 2 }, // 阴影偏移
    shadowOpacity: 1, // 阴影不透明度
    shadowRadius: 8, // 阴影半径
    elevation: 3, // 阴影深度
  },
  loginBox:{
    paddingTop:68,
  },
  titleContent:{
  },
  contentOne:{
    fontSize:28,
    fontWeight:'500',
    color:'#000000',
    fontFamily:'HarmonyOS_Sans_SC_Regular',
    marginBottom:8,
  },
  contentTwo:{
    fontSize:14,
    fontWeight:'400',
    fontFamily:'HarmonyOS_Sans_SC_Regular',
    color:'#8E8E93',
    marginBottom:18,
  },
  boxInput:{},
  input:{
    fontSize:16,
    borderBottomColor:'#F2F2F7',
    borderBottomWidth:1,
    paddingVertical:12,
    marginTop:16,
    color:'#000',
    fontFamily:'HarmonyOS_Sans_SC_Regular',
  },
  agreementBox:{
    flexDirection:'row',
    marginTop:34,
    alignItems:'center',
  },
  agreementBoxCheck:{
    flexDirection:'row'
  },
  agreementBoxCheckText:{
    color:'#8E8E93',
    fontSize:12,
    fontFamily:'HarmonyOS_Sans_SC_Regular',
    lineHeight:18
  },
  agreementBoxView:{},
  agreementBoxViewText:{
    fontSize:12,
    lineHeight:18,
    color:'#4371B1',
    fontFamily:'HarmonyOS_Sans_SC_Regular',
  },
  loginBtn:{
    width:'100%',
    alignItems:'center',
    justifyContent:'center',
    height:44,
    borderRadius:10,
    marginTop:18,
    overflow:'hidden'
  },
  loginBtnText:{
    fontSize:14,
    fontWeight:'500',
  },
  btnBottom:{
    flexDirection:'row',
    justifyContent:'space-between',
    marginTop:20,
  },
  btnBottomText:{
    fontSize:14,
    color:'#4371B1',
    fontFamily:'HarmonyOS_Sans_SC_Regular',
  },
  wxLoginBox:{
    flex:1,
    alignItems:'center',
    paddingTop:20,
  },
  textBox:{
    flexDirection:'row',
    alignItems:'center',
    justifyContent:'center',
    marginBottom:22,
  },
  boxLine:{
    width:80,
    height:1,
    backgroundColor:'#E5E5EA',
  },
  otherLoginText:{
    fontSize:12,
    color:'#8E8E93',
    paddingHorizontal:16,
  },


})
